package cn.chendd.ajax.controller;

import org.apache.tomcat.util.http.fileupload.FileUtils;
import org.springframework.http.ContentDisposition;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.naming.OperationNotSupportedException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * Ajax文件下载Controller接口定义
 *
 * @author chendd
 * @date 2024/7/21 17:02
 */
@RestController
@RequestMapping("/ajax/download")
public class AjaxDownloadController {

    @GetMapping("/yml")
    public void download(HttpServletResponse response) throws IOException {
        String attachment = ContentDisposition.attachment().filename(URLEncoder.encode("application.yml" , StandardCharsets.UTF_8.name())).build().toString();
        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION , attachment);
        try (InputStream inputStream = getClass().getResourceAsStream("/application.yml");
             ServletOutputStream outputStream = response.getOutputStream()) {
            assert inputStream != null;
            StreamUtils.copy(inputStream , outputStream);
        }
    }

    @GetMapping("/class")
    public ResponseEntity<byte[]> download() throws Exception {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDisposition(ContentDisposition.attachment().filename(URLEncoder.encode("中文文件名Controller.class" , StandardCharsets.UTF_8.name())).build());
        try (InputStream inputStream = getClass().getResourceAsStream(AjaxDownloadController.class.getSimpleName() + ".class")) {
            return ResponseEntity.ok().headers(headers).body(StreamUtils.copyToByteArray(inputStream));
        }
    }

}
